<?php
namespace server\trigger;

use server\SystemLogInterface;
use common\core\server\BaseEvent;
use common\core\server\BaseServer;
use common\core\server\BaseTrigger;
use common\core\server\TriggerInterface;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class OperationTrigger extends BaseTrigger implements TriggerInterface
{

    public $log;

    public function __construct(SystemLogInterface $log, array $config = [])
    {
        $this->log = $log;
        parent::__construct($config);
    }

    /**
     * 绑定事件名称
     * @return string
     */
    public static function name()
    {
        return BaseServer::EVENT_LOG_OPERATION;
    }

    /**
     * 执行
     *
     * @param BaseEvent $event
     *
     * @return mixed
     */
    public function run(BaseEvent $event)
    {
        //file_put_contents('./log.txt', date('Y-m-d H:i:s') . '==>' . 'login_log' . PHP_EOL, FILE_APPEND);

        try {
            $user = \Yii::$app->user->identity;
            $ip = \Yii::$app->request->getUserIP();
        } catch (\Exception $e) {
            $ip = '127.0.0.1';
            $user = [];
        }
        $appId = \Yii::$app->id;
        $module = \Yii::$app->controller->module;
        $uid = ArrayHelper::getValue($user, 'id', -2);
        $params = [
            'user_id'    => $uid,
            'user_info'  => !empty($user['username']) ? $user['username'] : '未知用户',
            'app_id'     => $appId,
            'version'    => (empty($module->module) || $module->module->id === $appId) ? "v0" : $module->module->id,
            'module'     => $module->id,
            'controller' => \Yii::$app->controller->id,
            'action'     => \Yii::$app->controller->action->id,
            'data'       => Json::encode($event->params),
            'ip'         => $ip,
            'created_at' => time(),
        ];

        $this->log->setOperationLog($params);
    }
}
